package com.weavernorth.humanresource;


import com.weavernorth.util.Logger4jUtil;
import org.apache.log4j.Logger;
import weaver.conn.RecordSet;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;

import java.math.BigDecimal;
import java.util.Calendar;


import weaver.general.BaseBean;
import weaver.general.Util;


import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.Iterator;


//年度调薪接口
public class HRNdtxAction implements Action {
//    public static Log log = LogFactory.getLog(HRNdtxAction.class.getName());
    @Override
    public String execute(RequestInfo requestInfo) {
        Logger log = Logger4jUtil.getLoggerByName("/action/HRNdtxAction/");
        log.info("年度调薪接口日志开始=======>");
        BaseBean bb = new BaseBean();
        //主表数据库
        RecordSet rs = new RecordSet();
        SalarRangeUtil salarRangeUtil = new SalarRangeUtil();
        boolean isSuccess = false;
        //获取当前日期
        Calendar now = Calendar.getInstance();
        int day = now.get(Calendar.DAY_OF_MONTH);
        String requestid = requestInfo.getRequestid();//请求ID
        String workflowid = requestInfo.getWorkflowid();//流程ID
        String tablename = requestInfo.getRequestManager().getBillTableName();//表单名称
        log.info("人事-年度调薪tablename的值是:" + tablename + "\n requestid" + requestid);


        //主表数据库字段
        String sxrq = "";//生效日期
        String sqyy = "";//申请原因
        String hblx = "";//货币类型
        String ygbh="";

        RecordSet mbrs = new RecordSet();//码表rs
        String mbsql = "";  //查询码表sql
        BigDecimal b_dqxssq=new BigDecimal("0.0");//地区系数（申请）
        BigDecimal b_xyznxssq=new BigDecimal("0.0");//行业职能系数（申请）
        BigDecimal b_dqbtsq=new BigDecimal("0.0");//地区补贴（申请）

        //1.获取主表单数据
        String sql = " select * from " + tablename + " where requestid =" + requestid;
        log.info("人事-年度调薪接口sql的值是:" + sql + "\n");
        rs.execute(sql);

        if (rs.next()) {

            sxrq = rs.getString("sxrq");//生效日期
            sqyy = "03";//rs.getString("sqyy");//申请原因
            hblx = "CNY";//rs.getString("hblx");//货币类型

            log.info("人事-年度调薪:生效日期sxrq的值是:" + sxrq + "\n");
            log.info("人事-年度调薪:申请原因sxrq的值是:" + sqyy + "\n");
            log.info("人事-年度调薪:货币类型sxrq的值是:" + hblx + "\n");

        }


        //2.封装sap请求xml
        StringBuffer xml = new StringBuffer("");


        xml.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:sap-com:document:sap:soap:functions:mc-style\">");

        xml.append("<soapenv:Header/>");
        xml.append("<soapenv:Body>");
        xml.append("<urn:Zhri074>");


        //Return字段
        xml.append("<Return>");
        xml.append("<item>");
        xml.append("<Type></Type>");
        xml.append("<Id></Id>");
        xml.append("<Number></Number>");
        xml.append("<Message></Message>");
        xml.append("<LogNo></LogNo>");
        xml.append("<LogMsgNo></LogMsgNo>");
        xml.append("<MessageV1></MessageV1>");
        xml.append("<MessageV2></MessageV2>");
        xml.append("<MessageV2></MessageV2>");
        xml.append("<MessageV3></MessageV3>");
        xml.append("<MessageV4></MessageV4>");
        xml.append("<Parameter></Parameter>");
        xml.append("<Row></Row>");
        xml.append("<Field></Field>");
        xml.append("<System></System>");
        xml.append("</item>");
        xml.append("</Return>");

        xml.append("<T0008>");


        //子表数据

        RecordSet dt1rs = new RecordSet();

        //1.获取子表单dt1数据
        String dt1sql = " select  * from " + tablename + "_dt1 dt1 " + " where dt1.mainid=( select id from " + tablename + " mt where mt.requestid =" + requestid + ")";

        log.info("人事-年度调薪接口dt1sql的值是:" + dt1sql + "\n");
        dt1rs.execute(dt1sql);

        while (dt1rs.next()) {
            //工资核算范围id
            String strGzfw = Util.null2String(rs.getString("xzfw"));
            //工资核算范围bpm值
            String strGzhsfw = salarRangeUtil.getGzfw(strGzfw);
            //zm 增加,判断工资范围是否锁定 开始

            String strLockMess = salarRangeUtil.judgeLock(strGzhsfw, sxrq);
            log.info("工资核算范围返回信息:" + strLockMess);
            if (!"".equals(strLockMess)) {
                strLockMess = strLockMess + "薪资核算结束后，工资范围解除锁定，流程可以继续提交";
                requestInfo.getRequestManager().setMessagecontent(strLockMess);
                return FAILURE_AND_CONTINUE;

            }


            //获取数据
             ygbh = dt1rs.getString("ygbh");//员工编号
            int xzlxInt = dt1rs.getInt("dqxzlxsq");//薪资类型(旧字段:"sqxzlx");
            log.info("薪资类型原值："+xzlxInt);
            //转码
            String xzlx = ""; //薪资类型
            switch (xzlxInt) {
                case 0:
                    xzlx = "10";
                    break;
            }
            log.info("薪资类型转码后的值:" + xzlx + "\n");
            int xzqyInt = dt1rs.getInt("dqxzqysq");//薪资区域(旧字段:"sqxzqy");
            int xzjbInt = dt1rs.getInt("dqxzjbsq");//薪资岗级别(旧字段：sqxzjb);
            int xzdcInt = dt1rs.getInt("dqxzdcsq");//"sqxzdc");//薪资岗档次
            BigDecimal jbgz = new BigDecimal(Util.null2s(dt1rs.getString("sqjbgz"), "0.0"));//基本工资
            BigDecimal jxgz = new BigDecimal(Util.null2s(dt1rs.getString("sqjxgz"), "0.0"));//绩效工资
            BigDecimal nzjjjs = new BigDecimal(Util.null2s(dt1rs.getString("sqndjj"), "0.0"));//年终奖金基数

            String xzjb = ""; //薪资岗级别
            mbsql = "select selectname from workflow_selectitem where fieldid = 17868 and selectvalue =" + xzjbInt;
            mbrs.execute(mbsql);
            if (mbrs.next()) {
                xzjb = mbrs.getString("selectname");
                log.info("薪资岗级别 sql的值:" + mbsql + "\n");
                log.info("薪资岗级别xzjb 的值:" + xzjb + "\n");
            }


            //****************薪资区域***************************

            String xzqy = ""; //薪资区域
            switch (xzqyInt) {

                case 0:
                    xzqy = "10";
                    break;
                case 1:
                    xzqy = "20";
                    break;
                case 2:
                    xzqy = "30";
                    break;

            }

            log.info("薪资区域xzqy 的值:" + xzqy + "\n");
            //********************************************


            //子表数据
            xml.append("<item>");
            xml.append("<IBegda>" + sxrq + "</IBegda>");//生效日期(!!!主表)
            xml.append("<IPernr>" + ygbh + "</IPernr>");//员工编号(子表)
            xml.append("<IPreas>" + sqyy + "</IPreas>");//申请原因(!!!!主表)
            xml.append("<ITrfar>" + xzlx + "</ITrfar>");//薪资类型(子表)
            xml.append("<ITrfgb>" + xzqy + "</ITrfgb>");//薪资区域(子表)
            xml.append("<ITrfgr>" + xzjb + "</ITrfgr>");//薪资岗级别(子表)
            xml.append("<ITrfst>" + xzdcInt + "</ITrfst>");//薪资岗档次(子表)


            xml.append("<IWaers>" + hblx + "</IWaers>");//货币类型(!!!主表)
            xml.append("<IZgz8001>" + jbgz + "</IZgz8001>");//基本工资(子表)
            xml.append("<IZgz8010>" + jxgz + "</IZgz8010>");//绩效工资(子表)
            xml.append("<IZgz8020>" + nzjjjs + "</IZgz8020>");//年终奖金基数(子表)
            xml.append("</item>");
            BigDecimal dqxssq = new BigDecimal(Util.null2s(dt1rs.getString("dqxssq"), "0.0"));
            b_dqxssq = b_dqxssq.add(dqxssq);
            log.info("地区系数（申请）：" + b_dqxssq);
            BigDecimal xyznxssq = new BigDecimal(Util.null2s(dt1rs.getString("xyznxssq"), "0.0"));
            b_xyznxssq = b_xyznxssq.add(xyznxssq);
            log.info("行业职能系数（申请）：" + b_xyznxssq);
            BigDecimal dqbtsq = new BigDecimal(Util.null2s(dt1rs.getString("dqbtsq"), "0.0"));
            b_dqbtsq = b_dqbtsq.add(dqbtsq);
            log.info("地区补贴（申请）：" + b_dqbtsq);

        }


        xml.append("</T0008>");
        //region[==新增字段==]
        xml.append("<T0014>");
        //地区系数(申请)存在值时
        if(b_dqxssq.compareTo(new BigDecimal("0.0"))==1){
            xml.append("<item>");
            xml.append("<Pernr>"+ygbh+"</Pernr>");
            xml.append("<Begda>"+sxrq+"</Begda>");
            xml.append("<Lgart>5025</Lgart>");
            xml.append("<Betrg></Betrg>");
            xml.append("<Anzhl>"+b_dqxssq+"</Anzhl>");
            xml.append("<Zeinh></Zeinh>");
            xml.append("<Preas>"+sqyy+"</Preas>");
            xml.append("</item>");
        }
        //行业只能系数(申请)存在值时：
        if(b_xyznxssq.compareTo(new BigDecimal("0.0"))==1){
            xml.append("<item>");
            xml.append("<Pernr>"+ygbh+"</Pernr>");
            xml.append("<Begda>"+sxrq+"</Begda>");
            xml.append("<Lgart>5100</Lgart>");
            xml.append("<Betrg></Betrg>");
            xml.append("<Anzhl>"+b_xyznxssq+"</Anzhl>");
            xml.append("<Zeinh></Zeinh>");
            xml.append("<Preas>"+sqyy+"</Preas>");
            xml.append("</item>");
        }
        //地区补贴(申请)不为空时
        if(b_dqbtsq.compareTo(new BigDecimal("0.0"))==1){
            xml.append("<item>");
            xml.append("<Pernr>"+ygbh+"</Pernr>");
            xml.append("<Begda>"+sxrq+"</Begda>");
            xml.append("<Lgart>5200</Lgart>");
            xml.append("<Betrg></Betrg>");
            xml.append("<Anzhl>"+b_dqbtsq+"</Anzhl>");
            xml.append("<Zeinh></Zeinh>");
            xml.append("<Preas>"+sqyy+"</Preas>");
            xml.append("</item>");
        }
        xml.append("</T0014>");
        //endregion
        xml.append("</urn:Zhri074>");
        xml.append("</soapenv:Body>");
        xml.append("</soapenv:Envelope>");


        log.info("人事-年度调薪接口XML的值是:" + xml.toString());


        //CommonToSapUtil commonToSapUtil=new CommonToSapUtil();
        try {
            //3.推送数据


            String txurl = Util.null2String(bb.getPropValue("personnel-erdos", "txurl"));


            //String responseXml=   commonToSapUtil.sendPost("rzurl", xml.toString(), "utf-8");
            String responseXml = salarRangeUtil.sendPost(txurl, xml.toString(), "utf-8");

            log.info("人事-年度调薪接SAP返回的值是:" + responseXml.toString());

            //===========SAP 返回解析====================

            String strWorkcode = "";

            //xmlStr为上图格式的字符串


            String EPernr = "";//员工编码
            String testType = "";
            String strMessage = "";
            Document doc = null;
            try {
                doc = DocumentHelper.parseText(responseXml.toString());
                Iterator<Element> its2 = doc.selectNodes("//Type").iterator();
                while (its2.hasNext()) {
                    Element element = its2.next();
                    testType = element.getText();
                    if (!"".equals(testType)) {
                        isSuccess = true;
                        log.info("推送成功testType值为:" + testType + "\n");
                        break;
                    }

                }
                //返回值失败时,则提示失败
                if ("E".equals(testType)) {
                    Iterator<Element> its3 = doc.selectNodes("//Message").iterator();
                    while (its3.hasNext()) {
                        Element element2 = its3.next();
                        strMessage = element2.getText();
                        if (!"".equals(strMessage)) {
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                log.info("接口返回信息格式化异常，异常信息：" + e.toString());
                log.info("接口执行结束=======>");
                e.printStackTrace();
                e.printStackTrace();
            }
            if ("S".equals(testType)) {
                log.info("提交成功！");
                log.info("接口执行结束=======>");
                return SUCCESS;
            } else {
                requestInfo.getRequestManager().setMessagecontent(strMessage);
                log.info("错误信息：" + strMessage);
                log.info("接口执行结束=======>");
                return FAILURE_AND_CONTINUE;
            }


        } catch (Exception e) {
            e.printStackTrace();
            log.info("年度调薪接口异常，异常信息：" + e.toString());
            log.info("接口执行结束=======>");
            return FAILURE_AND_CONTINUE;
        }


    }
}




